package codeTop;

import java.util.ArrayList;
import java.util.List;

public class topological {
    public List<Integer> sort(int[][] input,int n){
        int[][] grid = new int[n][n];
        int[] in = new int[n];
        for (int[] ints : input) {
            grid[ints[0]][ints[1]] = 1;
            in[ints[1]]++;
        }
        boolean[] visit = new boolean[n];
        int cnt = 0;
        List<Integer> list = new ArrayList<>();
        while (cnt < n) {
            boolean flag = false;
            for (int i = 0; i < n; i++) {
                if (in[i]==0&&!visit[i]){
                    flag = true;
                    visit[i] = true;
                    for (int j = 0; j < n; j++) {
                        if (grid[i][j] == 1) {
                            in[j]--;
                        }
                    }
                    list.add(i);
                    cnt++;
                }
            }
            if (!flag) {
                break;
            }
        }
        if (cnt == n) {
            return list;
        }else {
            return null;
        }
    }
}
